from posixpath import split
import sys, os
import struct

def main(argv):
    hexPath=""
    if len(argv) == 1:
        hexPath = argv[0]
    else:
        print("invalid argv")
        return -1
    
    print("hex Path:" + hexPath)
    if os.path.exists(hexPath) is False:
        print("exists wrong")
        return -2

    # 提取文件名, 然后断开后缀名
    fPathAndExt = os.path.splitext(hexPath)
    fname = fPathAndExt[0]
    print("fname:" + fname)
    
    hexFile = open(hexPath, 'r', encoding='UTF-8')
    imgFile = open(fname + '.img', 'wb')
    if imgFile.writable() == False:
        print("imgFile write failed.")
        return -3

    lastAddrStr = ""
    lineStr = hexFile.readline()
    print("===============")
    i = 1
    while len(lineStr) != 0:
        lineStr = lineStr[0:57]
        elems = lineStr.split(': ')
        if len(elems) != 2:
            lineStr = hexFile.readline()
            continue

        addrStr = elems[0]
        lineStr = elems[1]
        elems = lineStr.split(' ')
        num_elems = list(map(lambda x: int(x, base=16), elems))
        for x in num_elems:
            s = struct.pack('B', x) # B:unsigned char
            imgFile.write(s)
        
        if len(lastAddrStr) > 0:
            addrN = int(addrStr, base=16)
            lastAddrN = int(lastAddrStr, base=16)
            if(addrN - lastAddrN != 16):
                print("terrible wrong: " + str(addrN - lastAddrN))
                exit(-4)
        
        # if i >= 21890:
        #     print(str(i) + ".line[" + addrStr + "]:" + lineStr)
        
        if i % 10240 == 0:
            print(str(i) + ".line[" + addrStr + "]:" + lineStr)

        lineStr = hexFile.readline()
        if lineStr == '\n':
            lineStr = hexFile.readline()

        lastAddrStr = addrStr
        i += 1
    
    imgFile.close()
    print("end")


if __name__ == "__main__":
    main(sys.argv[1:])